import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class InputPage extends StatefulWidget {
  const InputPage({super.key});

  @override
  State<InputPage> createState() => _CalculatorPageState();
}

class _CalculatorPageState extends State<InputPage> {
  final TextEditingController _firstNumberController = TextEditingController();
  final TextEditingController _secondNumberController = TextEditingController();
  final TextEditingController _resultController = TextEditingController();
  String _errorMessage = '';

  // 创建实例
  final _platform = const MethodChannel('samples.flutter.dev/way1_add');

  //调用加法方式1-MethodChannel
  Future<String> Way1(num num1, num num2) async {
    // 调用方法 getBatteryLevel
    print('开启进行异步操作');
    num result = (await _platform
        .invokeMethod<int>('Way1', {'num1': num1, 'num2': num2})) as num;
    print('异步操作完成，计算结果为：$result');
    setState(() {
      _resultController.text = result.toString();
    });
    return '异步操作完成';
  }

  // 创建实例
  final _basicChannel = const BasicMessageChannel(
      "samples.flutter.dev/way2_mul", StandardMessageCodec());

  //调用加法方式2-BasicMessageChannel（貌似只能传递简单类型）
  Future<String> Way2(num num1, num num2) async {
    // 调用方法，获取平台侧的返回值
    String date = '$num1-$num2';
    num result = await _basicChannel.send(date) as num;
    print("BasicMessageChannel--$result");
    setState(() {
      _resultController.text = result.toString();
    });
    return '异步操作完成';
  }

  // 创建实例
  final _eventChannel = const EventChannel('samples.flutter.dev/way3_random');

  //调用加法方式3-EventChannel（原生向dart的单向通信）
  Future<String> Way3() async {
    num result = (await _platform.invokeMethod<int>('Way3')) as num;
    setState(() {
      _resultController.text = result.toString();
    });
    return '异步操作完成';
  }

  void registerWay3Listener() {
    // 注册事件监听
    _eventChannel.receiveBroadcastStream().listen((event) {
      print("xxx---EventChannel--$event");
      setState(() {
        _resultController.text = event.toString();
      });
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setListener();
    registerWay3Listener();
  }

  //设置监听原生端消息接收
  void setListener() {
    _basicChannel.setMessageHandler((message) async {
      print("接收到鸿蒙端发来的数据，数据为：$message");
    });
  }

  void _calculateSum(num way) {
    if (way == 3) {
      Way3();
      return;
    }
    setState(() {
      _errorMessage = '';
    });
    String firstNumberText = _firstNumberController.text;
    String secondNumberText = _secondNumberController.text;

    if (firstNumberText.isEmpty || secondNumberText.isEmpty) {
      setState(() {
        _errorMessage = '输入不能为空，请输入有效的数字。';
      });
      return;
    }

    double? firstNumber = double.tryParse(firstNumberText);
    double? secondNumber = double.tryParse(secondNumberText);

    if (firstNumber == null || secondNumber == null) {
      setState(() {
        _errorMessage = '输入不是有效的数字，请重新输入。';
      });
      return;
    }
    if (way == 1) {
      Way1(firstNumber, secondNumber);
    } else if (way == 2) {
      Way2(firstNumber, secondNumber);
    }
  }

  @override
  void dispose() {
    _firstNumberController.dispose();
    _secondNumberController.dispose();
    _resultController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('数字计算器'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              TextField(
                controller: _firstNumberController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: '第一个数字',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  filled: true,
                  fillColor: Colors.grey[200],
                ),
              ),
              const SizedBox(height: 20),
              TextField(
                controller: _secondNumberController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: '第二个数字',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  filled: true,
                  fillColor: Colors.grey[200],
                ),
              ),
              const SizedBox(height: 20),
              TextField(
                controller: _resultController,
                enabled: false,
                decoration: InputDecoration(
                  labelText: '计算结果',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  filled: true,
                  fillColor: Colors.grey[200],
                ),
              ),
              if (_errorMessage.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 10),
                  child: Text(
                    _errorMessage,
                    style: const TextStyle(color: Colors.red),
                  ),
                ),
              CustomCalculatorButton(
                text: '计算总和Way1-add-MethodChannel',
                onPressed: () {
                  _calculateSum(1);
                },
              ),
              CustomCalculatorButton(
                text: '计算总和Way2-mul-BasicMessageChannel',
                onPressed: () {
                  _calculateSum(2);
                },
              ),
              CustomCalculatorButton(
                text: '获取随机数Way3-EventChannel',
                onPressed: () {
                  _calculateSum(3);
                },
              ),
              CustomCalculatorButton(
                text: 'dart按钮跳转到cameraPage',
                onPressed: () {
                  Navigator.pushNamed(context, '/camera');
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 自定义按钮组件
class CustomCalculatorButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  const CustomCalculatorButton({
    super.key,
    required this.text,
    required this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const SizedBox(height: 20),
        ElevatedButton(
          onPressed: onPressed,
          style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 30),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
          child: Text(
            text,
            style: const TextStyle(fontSize: 16),
          ),
        )
      ],
    );
  }
}
